<?php

namespace CNEPAdmin\Controller;

use CNEPAdmin\Controller\CommonController;

class PrivModuleController extends CommonController {

    protected $_modelName = "PrivModule";

    protected function setCode() {
        $this->_code = 'System'; // 属于系统管理模块
    }

    public function index() {
        $this->display();
    }

    /////////权限模块的设置////////////////

    /**
     * 开发人员添加权限管理的页面
     */
    public function editSysPrivManage() {
        $this->checkPriv(md5('SuperHtml'), 2, false);

        $this->assign('moduleList', $this->getPrivModuleListForSelect());
        $this->assign('moduleListSelect', $this->_model->getModuleListForMenu());
        $this->display();
    }

    public function saveModule() {
        $this->checkPriv(md5('SuperHtml'), 2);
        $id = I("post.privID");

        if ($id > 0) {
            $this->_updateMsg();
        } else {
            $this->_addModule();
        }
    }

    /**
     * 同步角色权限到memcache中
     */
    public function synchPrivMod2Mem() {
        $this->checkPriv(md5('SuperHtml'), 2);

        S(C("CACHE_MEM"));
        $this->_setModel();
        $this->_model->sychronRolePriv();
        $this->_myAjaxReturn(1);
    }
    
//    public function fixPriv() {
//        $roleModList = D("SysRoleModule")->select();
//        $privList = D("PrivModule")->select();
//        
//        if($privList && $roleModList) {
//            
//        }
//        
//        
//    }

    /**
     *  添加
     */
    private function _addModule() {
        $this->_ajaxOperate('addModule');
    }

    /**
     * 更新信息
     */
    private function _updateMsg() {
        $this->_ajaxOperate('updateMsg');
    }

    /**
     * 删除
     */
    public function deleteModule() {
        $this->_ajaxOperate('deleteModule', md5('SuperHtml'), 2, I("privID"));
    }

    /**
     * 查看
     */
    public function getModuleById() {
        $this->checkPriv(md5('SuperHtml'), 2);

        $id = intval(I("privID", 0));
        $this->_setModel();
        $this->ajaxReturn($this->_model->getModule($id));
    }

    /**
     * 查看列表
     */
    public function getPrivModuleListForSelect() {
        $pid = intval(I("post.searchPid", 0));
        $relist = array();
        $list = $this->_getModuleListByPid($pid);

        if ($list) {
            $this->_dealPrivModuleListForSelect($list, $relist, 0);
        }

        return $relist;
    }

    private function _dealPrivModuleListForSelect($list, &$relist, $level) {
        static $i = 0;

        $times = $level;
        $temp = $level; // 保存到当前level
        $preStr = '';
        while ($times > 0) {
            $times --;
            $preStr .= "&nbsp;&nbsp;&nbsp;&nbsp;";
        }
//        echo $level . "," . (strlen($preStr) / 6) . PHP_EOL;

        foreach ($list as $val) {

            $relist[$i]['privID'] = $val['privID'];
            $relist[$i]['privCode'] = $val['privCode'];
            $relist[$i]['pid'] = $val['pid'];
            $relist[$i ++]['privName'] = $preStr . $val['privName'];
            $valList = $val['list'];

            if ($valList && count($valList) > 0) {
                $level ++;
                $this->_dealPrivModuleListForSelect($valList, $relist, $level);
            }
            $level = $temp;
        }
    }

    ///////////权限的设置///////////////////

    /**
     * 根据roleID得到该角色的所有权限
     */
    public function getPrivByRoleID() {
        $this->checkPriv('rolePriv', 1, false);

        $roleList = $this->_getRolePrivList(I("roleID"));
        $rejson = array();

        $rejson['result'] = 1;
        $rejson['list'] = $roleList;


        $this->ajaxReturn($rejson);
    }

    /**
     * 系统角色权限设置页,得到角色列表（用于下拉框），得到所有权限模块
     */
    public function sysRoleDetail() {
        $this->checkPriv('rolePriv', 1, false);

        $this->_setModel();
        $this->assign('sysRoleList', D("SysAdminRole")->where(array("isOn" => 1))->select());
        // 得到大模块列表
        $mList = $this->_getModuleListByPid(0);
        $this->assign('mList', $mList);
        $this->display();
    }

//
//    public function getModuleListByRidAndMid() {
//        $this->checkPriv('rolePriv', 2);
//
//        $moduleList = $this->_getModuleListByPid();
//        $privList = $this->_getRolePrivList();
//        if ($moduleList) {
//            $this->_deal($moduleList, $privList);
//        }
//
//        $list['moduleList'] = $moduleList;
////    $list['privList'] = $privList;
//        $this->ajaxReturn($list);
//    }
//
//    private function _deal(&$moduleList, $privList) {
//        $i = 0;
//        foreach ($moduleList as $val) {
//            $priv = 0;
//            if ($privList) {
//                foreach ($privList as $v) {
//                    if (intval($v['moduleID']) === intval($val['privID'])) {
//                        $priv = $v['priv'];
//                    }
//                }
//                // 如果list还有值
//                if (count($val['list']) > 0) {
//                    deal($val['list'], $privList);
//                    $moduleList[$i]['list'] = $val['list'];
//                }
//            }
//            $moduleList[$i++]['priv'] = $priv;
//        }
//    }

    /**
     * 修改系统角色权限
     */
    public function saveSysRolePriv() {
        $this->checkPriv('rolePriv', 2);

        $roleID = intval(I("post.roleID", -1));
        $rolePrivList = I('post.list'); // 格式： 

        if ($roleID > 0 && count($rolePrivList) > 0) {
            $rt = false;

            S(C("CACHE_MEM"));

            $rolePriv = D("SysRoleModule");

            $rolePriv->startTrans();

            foreach ($rolePrivList as $mArr) { // [{"key":"System",value:[{id:61,code:"sysAdmin",value:1},{...},...]},{...},...]
                foreach ($mArr['value'] as $privArr) {
                    $memKey = '_' . $roleID . '_' . $mArr['key'] . '_' . $privArr['code'];
                    S($memKey, $privArr['value']);

                    if ($rolePriv->isExistByRoleidAndMid($roleID, $privArr['id'])) { // 存在的话就更新
                        $where = array("roleID" => $roleID, "moduleID" => $privArr['id']);
                        $data = array("priv" => $privArr['value'], "memcacheKey" => $memKey, "other"=>$privArr['other']);
                        $rolePriv->updateOneByRoleidAndMid($where, $data);
                        $rt = true;
                    } else { // 否则添加
                        $data = array(
                            "roleID" => $roleID,
                            "moduleID" => $privArr['id'],
                            "priv" => $privArr['value'],
                            "memcacheKey" => $memKey,
							"other"=>$privArr['other']
                        );

                        $rt = $rolePriv->addRoleModulePriv($data);
                    }
                }
            }

            if ($rt === false) {
                $this->_error = $rolePriv->getError();
                $rolePriv->rollback();
            } else {
                $rolePriv->commit();
            }
        } else {
            $this->_error = "请指定系统角色并为其设置权限后,  再提交 ";
            $rt = false;
        }

        $this->_myAjaxReturn($rt);
    }

    /**
     * 更新该角色对指定大模块的权限,存在则更新，否则添加
     */
    private function _updateRolePrivModule($roleID = 0, $moduleName = '', $privStr = '') {
        $rt = false;
//        $roleID = intval(I("post.roleID", -1));
//        $moduleName = trim(I('moduleName'));
//        $privStr = trim(I('privStr')); // 格式：moduleid|priv,moduleid|priv...

        if ($roleID > 0 && strlen($privStr) > 0) {

            S(C("CACHE_MEM"));

            $rolePriv = D("SysRoleModule");
            $pri = D("PrivModule");

            $rolePriv->startTrans();

            $privArr = explode(',', $privStr);

            if ($privArr !== false && count($privArr) > 0) {

                foreach ($privArr as $val) {
                    $moduleArr = explode('|', $val); // 格式：moduleid|priv

                    if ($moduleArr !== false && count($moduleArr) > 0) {

                        $tmpArr = $pri->where(array("privID" => $moduleArr[0]))->field("privCode")->find();

                        if (!$tmpArr) {
                            $this->_error = "部分权限数据不存在" . $pri->getError();
                            $rolePriv->rollback();
                            return false;
                        } else {
                            $memKey = '_' . $roleID . '_' . $moduleName . '_' . $tmpArr['privCode'];

                            S($memKey, $moduleArr[1]);

                            if ($rolePriv->isExistByRoleidAndMid($roleID, $moduleArr[0])) { // 更新
                                $where = array("roleID" => $roleID, "moduleID" => $moduleArr[0]);
                                $data = array("priv" => $moduleArr[1], "memcache_key" => $memKey);
                                $rt = $rolePriv->updateOneByRoleidAndMid($where, $data);
                            } else { // 添加
                                $data = array(
                                    "roleID" => $roleID,
                                    "moduleID" => $moduleArr[0],
                                    "priv" => $moduleArr[1],
                                    "memcache_key" => $memKey,
                                );

                                $rt = $rolePriv->addRoleModulePriv($data);
                            }
//                            dump($rolePriv->getLastSql());
//                            dump($rt);
                        }

                        if ($rt === false) {
//                            dump("nima");
                            $this->_error = $rolePriv->getError();
                            $rolePriv->rollback();
                            return false;
                        } else {
                            $rolePriv->commit();
                        }
                    }
                }
            }
        } else {
            $this->_error = "请指定系统角色并为其设置权限后再提交 ";
            $rt = false;
        }

        return $rt;
    }

    /**
     * 根据 pid 得到其所有子模块列表 
     */
    private function _getModuleListByPidPrivate($pid, Array &$list) {
        $level = 0;

        $tmpList = $this->_model->where(array("pid" => $pid))->select();
        if ($tmpList) {

            foreach ($tmpList as $v) {
                $list[$level] = $v;
                $list[$level]['list'] = array(); // 用于存放子模块列表
                if ($v['isLeaf'] == 0) { // 如果还有子模块，得到其子模块
                    $this->_getModuleListByPidPrivate($v['privID'], $list[$level]['list']);
                }
                $level++;
            }
        }
    }

    /**
     * 得到 pid 的所有子模块
     * @param type $pid
     * @return boolean|array
     */
    private function _getModuleListByPid($pid = -1) {
        if ($pid < 0) {
            $pid = I("post.pid", -1);
        }

        if ($pid >= 0) {
            $this->_setModel();
            $list = array();
            $this->_getModuleListByPidPrivate($pid, $list);
            return $list;
        } else {
            $this->_error = "请选择系统管理模块";
            return false;
        }
    }

    /**
     * 得到指定系统角色对指定模块及其所有子模块的权限
     * @param type $roleID
     */
    private function _getRolePrivList($roleID = -1) {
        if ($roleID <= 0) {
            $roleID = intval(I('post.roleID', -1));
        }
        $list = false;
        if ($roleID > 0) {
            $sysMdl = D("SysRoleModule");
            $list = $sysMdl->where("roleID = $roleID")->field("roleModuleID,moduleID,priv,other")->select();
        }
        return $list;
    }

}
